import BaseMctApi from "@/framework/infra/base/BaseMctApi";
import TargetTypeEnum from "@/feature/mms/infra/constants/TargetTypeEnum";
import NoticeMsgEntity from "@/feature/mms/domain/entity/NoticeMsgEntity";
import {EventBus} from "@/framework/infra/event/EventBus";
import EventNames from "@/infra/event/EventNames";

let hasNotice = false

class NoticeApi extends BaseMctApi {
  constructor() {
    super('mms/notice-msg', NoticeMsgEntity)
  }

  myMsgList(data) {
    return this.sync().then(() => {
      return this.get('my-msg-list', data)
    })
  }

  read(id) {
    return this.post('read', {id})
  }

  readAll() {
    return this.post('read-all')
  }

  myMsgPage(data) {
    return this.sync().then(() => {
      return this.get('my-msg-page', data)
    })
  }

  notReadCount() {
    return this.get('not-read-count').then(data => {
      if (data > 0 && !hasNotice) {
        hasNotice = true
        EventBus.emit(EventNames.newMsg)
      }
      return data
    })
  }

  sync() {
    return this.post('sync')
  }

  create(data) {
    if (data.targetType === TargetTypeEnum.ROLE.id) {
      data.targetValue = data.targetRoleIdList
      if (!data.targetValue.length) {
        throw new Error('请选择角色')
      }
      for (const value of data.targetValue) {
        if (isNaN(value)) {
          throw new Error('请选择正确的角色')
        }
      }
    } else if (data.targetType === TargetTypeEnum.PERSON.id) {
      // debugger
      // data.targetValue = data.targetUserIdList.split(/[,|，]/ig)
      data.targetValue = data.targetUserIdList
      // if (!data.targetValue.length) {
      //   throw new Error('请输入用户ID')
      // }
      // for (const value of data.targetValue) {
      //   if (isNaN(value)) {
      //     throw new Error('请输入正确的用户ID')
      //   }
      // }
    }

    return this.post('create', data)
  }
}

export const noticeApi = new NoticeApi()
